package com.jiepos.mpos.biz.code.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.common.constant.DBConstant.Table;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.dao.AppAreaCdDao;
import com.jiepos.mpos.common.entity.App_Area_CdEntity;
import com.jiepos.mpos.core.entity.Pagination;
import com.jiepos.mpos.core.service.BaseService;
import com.jiepos.mpos.core.util.IDFactoryUtil;
import com.jiepos.mpos.core.util.StringUtils;

/**
 * 
 * 
 * <p>
 * 标题: —— 地区代码表服务类
 * </p>
 * <p>
 * 模块: 通用平台
 * </p>
 * <p>
 * 版权: Copyright (c) 2017 江苏杰博实信息技术有限公司
 * 
 * @author 张学涛
 * @version 1.0
 * @since 2017年9月15日下午1:54:29 @history（历次修订内容、修订人、修订时间等）
 */
@Service
public class AppAreaCdService extends BaseService {

	@Autowired
	private AppAreaCdDao appAreaCdDao;

	/**
	 * 查询地区代码列表json分页数据
	 * 
	 * @param pagination
	 * @param appAreaCdEntity
	 * @return
	 */
	public Map getAreaCdList(Pagination pagination, App_Area_CdEntity appAreaCdEntity) {
		StringBuffer sb = getInitSql("t1").append(",");
		sb.append(
				" t1.area_uuid as uuid, t1.area_cd,t1.area_cn_nm,t1.zipcd,t1.sup_area_cd||'-'||t2.area_cn_nm as sup_area_cd,t1.bank_area_cd,t1.level_no");
		sb.append(" from ");
		sb.append(Table.T_APP_AREA_CD);
		sb.append(" t1 LEFT JOIN ");
		sb.append(Table.T_APP_AREA_CD);
		sb.append(" t2 ON t1.sup_area_cd = t2.area_cd");
		sb.append(" where 1=1 ");
		List list = new ArrayList();
		if (!StringUtils.isBlank(appAreaCdEntity.getArea_cd())) {
			sb.append(" and t1.area_cd like ? ");
			list.add("%" + appAreaCdEntity.getArea_cd() + "%");
		}
		if (!StringUtils.isBlank(appAreaCdEntity.getArea_cn_nm())) {
			sb.append(" and t1.area_cn_nm like ? ");
			list.add("%" + appAreaCdEntity.getArea_cn_nm() + "%");
		}
		pagination.queryString = sb.toString();
		pagination = this.getOrderSql(pagination, "t1");
		return appAreaCdDao.getPaginationMap(pagination, "t1", list);
	}

	/**
	 * 地区树形结果
	 * 
	 * @param isOpen
	 *            是否打开，true打开，反之折叠
	 * @return
	 */
	public List<Map<String, Object>> getAreaTree() {
		StringBuffer sql = new StringBuffer();
		sql.append(
				"SELECT t1.area_uuid as \"uuid\",t1.area_cd ID,t1.sup_area_cd PID,t1.area_cd||'-'||t1.area_cn_nm as NAME")
				.append(" FROM ").append(Table.T_APP_AREA_CD).append(" t1 where 1 = 1");
		List<Map<String, Object>> areas = appAreaCdDao.queryForList(getOrderSql(sql.toString(), "t1"), null);
		return areas;
	}

	/**
	 * 保存地区代码
	 * 
	 * @param appAreaCdEntity
	 * @param map
	 */
	public void saveAreaCd(App_Area_CdEntity appAreaCdEntity, Map map) {
		appAreaCdEntity.setRec_upd_usr_id(String.valueOf(map.get(SystemConstant.SESSION_LOGIN_USER)));
		if (!StringUtils.isBlank(appAreaCdEntity.getArea_uuid())) {
			App_Area_CdEntity newAppAreaCdEntity = appAreaCdDao.findByParam("area_uuid",
					appAreaCdEntity.getArea_uuid());
			appAreaCdEntity.setRec_upd_ts(new Timestamp(System.currentTimeMillis()));
			appAreaCdEntity.setRec_id(newAppAreaCdEntity.getRec_id());
			appAreaCdEntity.setLast_oper_in(SystemConstant.OPER_UPDATE);
			List noChangeList = new ArrayList();
			noChangeList.add("area_uuid");
			noChangeList.add("rec_crt_ts");
			appAreaCdDao.update(appAreaCdEntity, noChangeList);
		} else {
			appAreaCdEntity.setRec_crt_ts(new Timestamp(System.currentTimeMillis()));
			appAreaCdEntity.setRec_upd_ts(new Timestamp(System.currentTimeMillis()));
			appAreaCdEntity.setArea_uuid(IDFactoryUtil.getUUID());
			appAreaCdEntity.setRec_st(SystemConstant.NORMAL_STATUS);
			appAreaCdEntity.setLast_oper_in(SystemConstant.OPER_ADD);
			appAreaCdDao.save(appAreaCdEntity);
		}
	}

	/**
	 * 根据记录id查询实体对象
	 * 
	 * @param area_uuid
	 * @return
	 */
	public Map getAreaCdById(String area_uuid) {
		if (StringUtils.isBlank(area_uuid) || area_uuid.equals("undefined")) {
			return new HashMap();
		}
		StringBuilder sb = new StringBuilder();
		sb.append(
				"select t1.area_uuid, t1.area_cd,t1.area_cn_nm,t1.area_en_nm,t1.zipcd,t1.sup_area_cd,t1.sup_area_cd||'-'||t2.area_cn_nm as cdAndName,t1.bank_area_cd,t1.level_no");
		sb.append(" from ");
		sb.append(Table.T_APP_AREA_CD);
		sb.append(" t1 LEFT JOIN ");
		sb.append(Table.T_APP_AREA_CD);
		sb.append(" t2 ON t1.sup_area_cd = t2.area_cd");
		sb.append(" where t1.rec_st!='");
		sb.append(SystemConstant.DEL_STATUS);
		sb.append("' and t1.area_uuid='");
		sb.append(area_uuid + "'");
		return appAreaCdDao.queryForMap(sb.toString());
	}

	/**
	 * 根据记录id集合删除数据
	 * 
	 * @param area_uuids
	 */
	public void deleteAreaCdByIds(String area_uuids) {
		appAreaCdDao.deleteByStatus("area_uuid", area_uuids);
	}

	/**
	 * 校验地区代码
	 * 
	 * @param appAreaCdEntity
	 * @return
	 */
	public String checkAreaCd(App_Area_CdEntity appAreaCdEntity) {
		StringBuilder sb = new StringBuilder();
		sb.append("select t1.area_uuid, t1.area_cd,t1.area_cn_nm from ");
		sb.append(Table.T_APP_AREA_CD);
		sb.append(" t1 where 1=1 ");
		List list = new ArrayList();
		if (!StringUtils.isBlank(appAreaCdEntity.getArea_cd())) {
			sb.append(" and t1.area_cd = ? ");
			list.add(appAreaCdEntity.getArea_cd());
		}
		if (!StringUtils.isBlank(appAreaCdEntity.getArea_uuid())) {
			sb.append(" and t1.area_uuid != ? ");
			list.add(appAreaCdEntity.getArea_uuid());
		}
		List result = appAreaCdDao.queryForList(sb.toString(), list);
		if (result.size() == 0 || result == null) {
			return SystemConstant.SUCCESS;
		}
		return SystemConstant.ERROR;
	}

	/**
	 * 获取地区
	 * 
	 * @return
	 */
	public List getAreaInfo() {
		
		StringBuffer sqlBuf = new StringBuffer();
		List sqlList = new ArrayList<>();
		List dataList = new ArrayList<>();
		sqlBuf.append(" select area_cd as \"area_cd\",area_cn_nm as \"area_cn_nm\" from  ").append(Table.T_APP_AREA_CD)
				.append(" where level_no = ? and rec_st != ?");
		sqlList.add(1);
		sqlList.add(SystemConstant.REC_ST_0);
		List<Map<String, Object>> result = appAreaCdDao.queryForList(sqlBuf.toString(), sqlList);
		StringBuffer sqlBuf2 = new StringBuffer();
		sqlBuf2.append(" select area_cd as \"area_cd\",area_cn_nm as \"area_cn_nm\",sup_area_cd as \"sup_area_cd\" from  ").append(Table.T_APP_AREA_CD)
				.append(" where level_no = ? and rec_st != ?");
		sqlList.clear();
		sqlList.add(2);
		sqlList.add(SystemConstant.REC_ST_0);
		List<Map<String, Object>> result1 = appAreaCdDao.queryForList(sqlBuf2.toString(), sqlList);
		sqlList.clear();
		sqlList.add(3);
		sqlList.add(SystemConstant.REC_ST_0);
		List<Map<String, Object>> result2 = appAreaCdDao.queryForList(sqlBuf2.toString(), sqlList);
		for (Map r : result) {
				List<Map<String, Object>> citys = new ArrayList<>();
				String area_cd = StringUtils.objToString(r.get("area_cd"));
				for (Map r1 : result1) {
					if (r1.get("sup_area_cd") != null && area_cd != null && r1.get("sup_area_cd").equals(area_cd)) {
						List<Map<String, Object>> countys = new ArrayList<>();
						String area_cd2 = StringUtils.objToString(r1.get("area_cd"));
						for (Map r2 : result2) {
							if (r2.get("sup_area_cd") != null && area_cd2 != null
									&& r2.get("sup_area_cd").equals(area_cd2)) {
								countys.add(r2);
							}
							r1.put("countys", countys);
						}
						citys.add(r1);
					}
					r.put("citys", citys);
				}
				dataList.add(r);
			}
		return dataList;
	}
	
	/**
	 * 根据区域编码查询出直接和间接父级编码
	 * @param code
	 * @return
	 */
	public Map<String, Object> getSupAreaByCode(String code){
		String sql = "SELECT AC.LEVEL_NO, AC.AREA_CD, AC.SUP_AREA_CD, SAC.SUP_AREA_CD SSUP_AREA_CD FROM T_APP_AREA_CD AC LEFT JOIN T_APP_AREA_CD SAC ON AC.SUP_AREA_CD = SAC.AREA_CD WHERE AC.AREA_CD = ?";
		List<Map<String, Object>> list = appAreaCdDao.queryForListMap(sql, new Object[]{code});
		return list != null && !list.isEmpty() ? list.get(0) : new HashMap<String, Object>();
	}
}
